<template xmlns="">
  <view class="page-container">
    <!-- 参与者部分 -->
    <view class="participant-section">
      <view class="participant-label">参与者</view>
      <view class="participants">
        <image v-for="item in roomUsers"
               @click="headSheet.headImgClikc(item)"
               class="participant-avatar"
               :src="proxy.$tool.getResources(item.avatar)"
               mode="aspectFill"/>
      </view>
    </view>
    <up-button type="success" text="功能介绍" @click="introducePopup.open()"></up-button>
    <view class="room-info">
      <up-form ref="userForm" :model="room" :rules="rules" labelPosition="top" labelWidth="100%">
        <!-- 房间号 -->
        <up-copy :content="room.roomId">
          <up-form-item
              label="房间号(点击复制分享给好友))"
              prop="roomId"
              borderBottom>
            <text> {{ room.roomId }}</text>
          </up-form-item>
        </up-copy>
        <!-- 计分模式 -->
        <up-form-item
            label="计分模式"
            prop="mode"
            borderBottom>
          <up-radio-group
              v-model="room.mode"
              @change="sendRuleChangeMsg"
              placement="row">
            <up-radio :key="0" label="统一记" :name="0"></up-radio>
            <up-radio :key="1" label="给分模式" :name="1"></up-radio>
            <up-radio :key="2" label="总账模式" :name="2"></up-radio>
          </up-radio-group>
        </up-form-item>
        <!-- 台费规则 -->
        <up-form-item
            label="台费规则"
            prop="taiwanFee"
            borderBottom>
          <up-radio-group
              v-model="room.taiwanFee"
              @change="sendRuleChangeMsg"
              placement="row">
            <up-radio :key="0" label="无台费" :name="0"></up-radio>
            <up-radio :key="1" label="抽分模式" :name="1"></up-radio>
            <up-radio :key="2" label="百分比" :name="2"></up-radio>
          </up-radio-group>
        </up-form-item>
        <!-- 最大台费 -->
        <up-form-item
            label="最大台费"
            v-if="room.taiwanFee===1 || room.taiwanFee===2"
            prop="taiwanFeeMax"
            borderBottom>
          <up-input
              type="number"
              placeholder="请输入"
              border="surround"
              @blur="sendRuleChangeMsg"
              v-model="room.taiwanFeeMax"
          ></up-input>
        </up-form-item>
        <!-- 百分比值 -->
        <up-form-item
            label="百分比值%"
            v-if="room.taiwanFee===2"
            prop="percentValue"
            borderBottom>
          <up-input
              type="number"
              placeholder="请输入"
              border="surround"
              @blur="sendRuleChangeMsg"
              v-model="room.percentValue"
          ></up-input>
        </up-form-item>
        <!-- 抽分模式配置 -->
        <up-form-item
            label="满"
            v-if="room.taiwanFee===1"
            prop="fullVal"
            borderBottom>
          <up-input
              type="number"
              placeholder="请输入"
              border="surround"
              @blur="sendRuleChangeMsg"
              v-model="room.fullVal"
          ></up-input>
        </up-form-item>
        <!-- 抽分模式配置 -->
        <up-form-item
            label="抽"
            v-if="room.taiwanFee===1"
            prop="deductVal"
            borderBottom>
          <up-input
              type="number"
              placeholder="请输入"
              border="surround"
              @blur="sendRuleChangeMsg"
              v-model="room.deductVal"
          ></up-input>
        </up-form-item>

      </up-form>
    </view>

    <!-- 开始计分按钮 -->
    <view class="room-btns">
      <view class="start-button" v-if="room.createUser===userInfo.id" type="primary" @click="startScoring()">
        好友加入房间后，开始计分
      </view>
      <view class="dissolve-room" v-if="room.createUser===userInfo.id" @click="verifyModal.dissolveRoomVerify()">
        解散房间
      </view>
      <view class="quit-room" v-else @click="quitRoom()">退出房间</view>
    </view>

    <up-modal
        :show="verifyModal.show"
        :title="verifyModal.title"
        :showCancelButton="true"
        @confirm="verifyModal.dissolveRoom()"
        @cancel="()=>{verifyModal.show=false}">
      <view class="slot-content">
        <rich-text :nodes="verifyModal.content"></rich-text>
      </view>
    </up-modal>


    <!-- 设置头像点击操作功能 -->
    <up-action-sheet
        :closeOnClickOverlay="true"
        :closeOnClickAction="true"
        @select="headSheet.selectClick"
        @close="headSheet.show=false"
        :actions="headSheet.list"
        :title="headSheet.title"
        :show="headSheet.show"></up-action-sheet>


    <up-popup
        :show="introducePopup.show"
        :round="10"
        :closeOnClickOverlay="true"
        @close="introducePopup.close"
        @open="introducePopup.open">
      <view class="introducePopup">
        <instructionsModule></instructionsModule>
      </view>
    </up-popup>

  </view>
</template>

<script setup>
import {ref, computed, getCurrentInstance} from "vue";
import {useStore} from "vuex";
import {onLoad, onUnload} from "@dcloudio/uni-app"; // 正确导入 onLoad
import WebSocket from '/common/socket.js';
import instructionsModule from "@/components/instructionsModule.vue";
const {proxy} = getCurrentInstance();
const store = useStore();
const userInfo = computed(() => store.state.userInfo);

//定义ws
let ws = null;


//定义房间信息表
const room = ref({
  roomId: 0,
  mode: 0,
  //抽分模式
  taiwanFee: 0,
  fullVal: 8,
  deductVal: 1,
  //百分比值
  percentValue: 1,
  //台费最大值
  taiwanFeeMax: 1,
});

//定义头像操作按钮数据
const headSheet = ref({
  //最终展示的菜单列
  list: [],
  //房主需要展示的菜单列
  hostList: [
    {name: '踢出房间', code: 0},
  ],
  //房客需要展示的菜单列
  userList: [],
  title: "",
  show: false,
  //当前选中的用户
  userId: null,
  //点击激活方法
  headImgClikc: user => {
    //判断是否点击的是自己
    if (user.userId === userInfo.value.id) {
      return;
    }
    //判断当前用户是否房主
    if (room.value.createUser !== userInfo.value.id) {
      //不是房主
      headSheet.value.list = headSheet.value.userList;
    } else {
      headSheet.value.list = headSheet.value.hostList;
    }
    headSheet.value.title = user.name;
    headSheet.value.userId = user.userId;
    headSheet.value.show = true;

  },
  //点击菜单回调
  selectClick: item => {
    switch (item.code) {
        //退出房间
      case 0:
        proxy.$request.post(`/bus-room/kickOutRoom/${room.value.roomId}/${headSheet.value.userId}`)
    }
  }
})


const rules = ref({
  roomId: [
    {
      type: "number",
      required: true, message: "房间号不能为空", trigger: ['blur', 'change']
    },
  ],
  mode: [
    {
      type: "number",
      required: true, message: "计分模式不能为空", trigger: ['blur', 'change']
    },

  ],
  taiwanFee: [
    {
      type: "number",
      required: true, message: "台费规则不能为空", trigger: ['blur', 'change'],
    },
  ],
  fullVal: [
    {
      type: "number",
      required: true, message: "抽分规则不能为空", trigger: ['blur', 'change'],
    },
  ],
  deductVal: [
    {
      type: "number",
      required: true, message: "抽分规则不能为空", trigger: ['blur', 'change'],
    },
  ],
  taiwanFeeMax: [
    {
      required: true, message: "最大台费不能为空", trigger: ['blur', 'change'],
    },
  ],
  percentValue: [
    {
      required: true, message: "台费规则百分比值不能为空", trigger: ['blur', 'change'],
    },
  ],
});
//定义房间用户集合
const roomUsers = ref([]);


//定义页面加载事件
onLoad((options) => {
  const id = options.id; // 获取参数 id
  if (id) {
    //存在id查询
    proxy.$request.get(`/bus-room/get-by-id/${id}`).then(res => {
      room.value = res;
      roomUsers.value = res.roomUsers;
      //连接socket
      initSocket(id);
    })
  } else {
    //不存在-直接创建
    createRoom();

  }
});

/**
 * 离开页面前的回调
 */
onUnload(() => {
  //离开页面关闭socket连接
  ws.close();
})


//初始化socket
const initSocket = (roomId) => {
  // ws = new WebSocket(`/${roomId}/${userInfo.value.id}`);
  ws = WebSocket.getInstance(`/${roomId}/${userInfo.value.id}`)
  // 注册消息处理函数
  ws.onMessage((msg) => {
    //定义数组下标
    let index = 0;
    //定义当前用户
    let user = null;
    //判断消息类型
    switch (msg.type) {
      case "0": //加入房间
        index = roomUsers.value.findIndex(item => item.userId === msg.data.userId);
        if (index === -1) {
          //加入房间
          roomUsers.value.push(msg.data)
          uni.$u.toast(`${msg.data.name}加入了房间`)
        }
        break;
      case "1": //退出房间
        user = removeRoomUsers(msg.data)
        if (user) {
          //移除成功
          uni.$u.toast(`${user.name}退出了房间`)
        }
        break;
      case "2": //解散房间
        uni.$u.toast(`房主解散了房间,即将回到首页！`)
        setTimeout(() => {
          uni.navigateBack({
            delta: 1
          })
        }, 1000)
        break;
      case "3":
        if (userInfo.value.id !== msg.sendUserId) {
          uni.$u.toast(`房主开启了比赛积分，即将跳转到积分页面！`)
          setTimeout(() => {
            //加入成功切换到房间页面去
            uni.navigateTo({
              url: `/pages/scoring/scoring?id=${roomId}`
            })
          }, 1000)
        }

        break;
      case "4":
        //从用户列表中移除
        user = removeRoomUsers(msg.data)
        if (user != null) {
          //找到用户
          if (userInfo.value.id === msg.data) {
            //当前用户就是被踢的人
            uni.$u.toast(`你已被房主踢出房间，即将退出房间！`)
            setTimeout(() => {
              //加入成功切换到房间页面去
              uni.navigateBack({
                delta: 1
              })
            }, 1000)
          } else {
            uni.$u.toast(`${user.name}被房主踢出房间！`)
          }
        }
      case "7":
        //房间规则变化消息-房主不修改
        if (userInfo.value.id !== msg.sendUserId) {
          //发送人是当前用户才需要改变房间状态
          room.value.mode = msg.data.mode
          room.value.taiwanFee = msg.data.taiwanFee
          room.value.fullVal = msg.data.fullVal
          room.value.deductVal = msg.data.deductVal
          room.value.percentValue = msg.data.percentValue
          room.value.taiwanFeeMax = msg.data.taiwanFeeMax
        }
        break;
    }
  });
}


/**
 * 通过用户id移除某个用户
 */
const removeRoomUsers = userId => {
  let index = roomUsers.value.findIndex(item => item.userId === userId);
  if (index !== -1) {
    const user = roomUsers.value[index];
    // 如果找到了该对象的索引，使用 splice 删除
    if (index !== -1) {
      roomUsers.value.splice(index, 1);
      //移除成功，返回被移除的用户
      return user
    } else {
      //移除失败
      return null;
    }
  }
  return null;
}


//创建一个房间
const createRoom = () => {
  proxy.$request.post("/bus-room/createRoom").then(res => {
    room.value = res;
    roomUsers.value = res.roomUsers;
    //连接socket
    initSocket(res.roomId);
  })
}

//定义确认弹框
const verifyModal = ref({
  title: '解散房间',
  content: '解散房间后，加入的人将会全部退出房间，是否继续？',
  show: false,
  /**
   * 解散房间确认
   */
  dissolveRoomVerify: () => {
    verifyModal.value.title = '解散房间';
    verifyModal.value.content = '解散房间后，加入的人将会全部退出房间，是否继续？';
    verifyModal.value.show = true;
  },
  /**
   * 解散房间
   */
  dissolveRoom: () => {
    proxy.$request.del(`/bus-room/dissolveRoom/${room.value.roomId}`).then(() => {
      //解散后收到消息通知回到上一页
      verifyModal.value.show = false
    })
  }
})
/**
 * 退出房间
 */
const quitRoom = () => {
  proxy.$request.post(`/bus-room/quitRoom/${room.value.roomId}`).then(() => {
    //解散成功-回到首页
    uni.switchTab({
      url: '/pages/index'
    });
  })
}


//创建表单引用
const userForm = ref(null);

/**
 * 开始计分
 */
const startScoring = () => {
  userForm.value.validate().then(valid => {
    if (valid) {
      proxy.$request.post(`/bus-room/startScoring`, {
        roomId: room.value.roomId,
        mode: room.value.mode,
        taiwanFee: room.value.taiwanFee,
        fullVal: room.value.fullVal,
        deductVal: room.value.deductVal,
        percentValue: room.value.percentValue,
        taiwanFeeMax: room.value.taiwanFeeMax,
      }).then(() => {
        //切换开始页面
        //加入成功切换到房间页面去
        uni.navigateTo({
          url: `/pages/scoring/scoring?id=${room.value.roomId}`
        })
      })
    }
  })

}


/**
 * 发送规则变化消息
 */
const sendRuleChangeMsg = () => {
  proxy.$request.post(`/bus-room/roomRuleChangeMessage`, {
    roomId: room.value.roomId,
    mode: room.value.mode,
    taiwanFee: room.value.taiwanFee,
    fullVal: room.value.fullVal,
    deductVal: room.value.deductVal,
    percentValue: room.value.percentValue,
    taiwanFeeMax: room.value.taiwanFeeMax,
  })
}


const introducePopup = ref({
  show: false,
  //打开
  open: () => {
    introducePopup.value.show = true;

  },
  //关闭
  close: () => {
    introducePopup.value.show = false;
  }
})


</script>
<style lang="less" scoped>

.page-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px;
  background-color: #f5f5f5;
  height: 100vh;
  box-sizing: border-box;

  .participant-section {
    display: flex;
    align-items: center;
    width: 100%;
    margin-bottom: 16px;
    padding: 0 16px;

    .participant-label {
      font-size: 14px;
      color: #333;
      margin-right: 10px;
    }

    .participants {
      display: flex;
      align-items: center;

      .participant-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        margin-right: 8px;
      }

      .add-participant {
        width: 40px;
        height: 40px;
        border: 1px dashed #ccc;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #888;
      }
    }
  }

  .room-info {
    margin-top: 10px;
    width: 100%;
    height: 100vh;
    overflow-y: auto;
    margin-bottom: 120px;
  }


  .room-btns {
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
    display: flex;
    justify-content: center; /* 水平居中 */
    align-items: center; /* 垂直居中 */
    position: absolute;
    bottom: 10px;

    .start-button {
      flex: 1;
      display: flex;
      justify-content: center; /* 水平居中 */
      align-items: center; /* 垂直居中 */
      width: 80%;
      height: 60px;
      background-color: #1aad19;
      color: #fff;
      border-radius: 10px;
      font-size: 16px;
      margin-bottom: 20px;
      margin-right: 20px;
    }

    .dissolve-room {
      color: #FF5722;
      margin-bottom: 16px;
      text-align: center;
      font-size: 18px;
    }

    .quit-room {
      color: #FF5722;
      margin-bottom: 16px;
      text-align: center;
      font-size: 18px;
    }
  }

  .introducePopup{
    height: 70vh;
    width: 100%;
    overflow-y: auto;
  }
}


</style>